package com.wenli.graduate2022.wenliGreenShop.repository.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wenli.graduate2022.wenliGreenShop.entity.Product;
import com.wenli.graduate2022.wenliGreenShop.entity.Property;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author HuangHai
 * @date 2021/10/8 17:29
 */
@Repository
public interface PropertyMapper {

    @Results(id = "property",value={
            @Result(property = "propertyCategory",column = "property_category_id",//根据数据库中的product_category_id字段作为条件，将查到的数据封装到productCategory属性里
                    one = @One(select = "com.wenli.graduate2022.wenliGreenShop.repository.mapper.CategoryMapper.findById",
                            fetchType = FetchType.LAZY))//懒加载，除非详细查看，如调用get方法，才会进行sql执行（打印对象其实是只要重写toString方法也是调用了get方法）
    })
    @Select("select * from property")
    List<Property> findAll();

    //根据种类查找属性------------------
    @Select("select * from property where property_category_id = #{id}")
    @ResultMap("property")
    List<Property> findByCategoryId(Integer id);

    @Select("select * from property")
    @ResultMap("property")
    IPage<Property> findByPage(Page page);

    @Select("select * from property where proper_name like concat('%',#{name},'%')")
    @ResultMap("property")
    List<Property> findByName(String name);

    //查询单个种类的属性时不能用这个方法，要用上面的findByCategoryId才行
    @Select("select * from property where property_id = #{id}")
    @ResultMap("property")
    Property findById(Integer id);

    @Insert("insert into property(property_name,property_category_id) values(#{propertyName},#{propertyCategory.categoryId})")
    @Options(useGeneratedKeys = true, keyProperty = "propertyId",keyColumn = "property_id")
    @ResultMap("property")
    int insert(Property property);

    @Update("update property set property_name=#{propertyName},property_category_id=#{propertyCategory.categoryId} where property_id = #{propertyId}")
    @ResultMap("property")
    int update(Property property);

    @Delete("delete from property where property_id = #{id}")
    @ResultMap("property")
    int delete(Integer id);

    /**
     * 根据category的name查出categoryID，再根据id查出该category的所有property
     * @param name
     * @return
     */
    @Select("select * from property where property_category_id = (select category_id from category where category_name = #{name})")
    @ResultMap("property")
    List<Property> selectByCategoryName(String name);


}
